//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using OpenLS.Spreadsheet.Expressions;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class SharedFormulaDictionary<TExpression> where TExpression : SharedExpression
    {
        private readonly Dictionary<CellAddress, TExpression> _cellToFormula =
            new Dictionary<CellAddress, TExpression>(new CellAddressComparer());

        private readonly List<TExpression> _expressions = new List<TExpression>();

        public TExpression this[CellAddress address]
        {
            get
            {
                TExpression result;
                if (_cellToFormula.TryGetValue(address, out result))
                    return result;
                foreach (TExpression expression in _expressions)
                {
                    if (expression.Address.Contains(address))
                        return expression;
                }
                throw new NotSupportedException("shared formula");
            }
        }

        public void Add(TExpression expression)
        {
            _cellToFormula.Add(expression.Address.TopLeft, expression);
            _expressions.Add(expression);
        }
    }
}